package com.example.coreshopapp.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.R;
import com.example.coreshopapp.adapter.OrderFormAdapter;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.GoodsCategoryData;
import com.example.coreshopapp.bean.OrderListBean;
import com.example.coreshopapp.bean.OrderListReq;
import com.example.coreshopapp.databinding.ActivityOrderFormBinding;
import com.example.coreshopapp.task.OrderListTask;
import com.example.coreshopapp.utils.FormDataUtils;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.TimeUtils;
import com.example.coreshopapp.weight.CustomDatePickerDialog;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;
import java.util.List;

public class OrderFormActivity extends BaseActivity {
    private ActivityOrderFormBinding binding;
    private OrderFormAdapter orderFormAdapter;
    private int page = 1;
    private int limit = 20;
    private boolean isLoading = false;
    private OrderListReq orderListReq = new OrderListReq(1, 999);
    private List<OrderListBean> orderList = new ArrayList<>();
    private CustomDatePickerDialog startDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_form);
        binding = ActivityOrderFormBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideTopBar();
        initView();
        viewClick();

        getInitRequest();
    }

    private void getInitRequest() {
        resetTime();
        getOrderList();
    }

      private  ArrayList<String> objects = new ArrayList<>();
    private void resetTime() {
        objects.clear();
        String startTime = TimeUtils.getDateOffset(-30, "yyyy-MM-dd");
        objects.add(startTime);
        objects.add(TimeUtils.getCurrentTime().toString().substring(0, 10));
        orderListReq.setPaymentTime(objects);
        binding.timeTv.setText(startTime);
        binding.timeTv.setVisibility(View.VISIBLE);

        binding.endTimeTv.setText(TimeUtils.getCurrentTime().toString().substring(0, 10));
        binding.endTimeTv.setVisibility(View.VISIBLE);
    }

    @SuppressLint("HandlerLeak")
    private Handler orderListHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    orderList = JSON.parseArray(msg.obj.toString(), OrderListBean.class);
                    binding.orderList.setVisibility(orderList.size() > 0 ? View.VISIBLE : View.GONE);
                    binding.formNone.setVisibility(orderList.size() > 0 ? View.GONE : View.VISIBLE);
                    orderFormAdapter.updateOrderFormAdapter(orderList);
                    break;
                case 9901:
                    Toast.makeText(OrderFormActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(OrderFormActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(OrderFormActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        orderFormAdapter = new OrderFormAdapter(orderList);
        orderFormAdapter.setOnItemClickListener(orderItemClick);
        binding.orderList.setAdapter(orderFormAdapter);
//        binding.orderList.addOnScrollListener(orderListScroll);
    }
    public void checkTime (String type) {
        startDialog = new CustomDatePickerDialog(this, 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth) -> {
            orderListReq = new OrderListReq(1, 999);
//                ArrayList<String> objects = new ArrayList<>();
            String time = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
            if (type == "start") {
                if(!TimeUtils.startValidate(time,objects.get(1))) {
                    showtoast(this,"起始日期不能大于结束日期");
                    return;
                }
            objects.set(0,time);
            binding.timeTv.setText(time );
//            binding.timeTv.setText(time + " 至 " + TimeUtils.getCurrentTime().toString().substring(0, 10));
            binding.timeTv.setVisibility(View.VISIBLE);
            } else {
                if(!TimeUtils.beforeValidate(time)) {
                    showtoast(this,"结束日期不能大于当前日期");
                    return;
                }
                if (!TimeUtils.startValidate(objects.get(0),time)) {
                    showtoast(this,"结束日期不能小于起始日期");
                    return;
                }
                objects.set(1,time);
                binding.endTimeTv.setText(time);
                binding.endTimeTv.setVisibility(View.VISIBLE);
            }
            orderListReq.setPaymentTime(objects);
//          objects.add(TimeUtils.getCurrentTime().toString().substring(0, 10));
//          getOrderList();
        }, TimeUtils.getYear(), TimeUtils.getMonth() - 1, TimeUtils.getDay(), false);
        startDialog.show();
    }



    private void viewClick() {
        binding.idTvStardate.setOnClickListener(view -> {
            // 起止日期
            checkTime("start");
        });
        binding.idTvEndDate.setOnClickListener(view -> {
            // 结束日期
            checkTime("end");
        });
        // 重置
        binding.btnReset.setOnClickListener(view -> {
            resetTime();
            orderListReq = new OrderListReq(1, 999);
//            binding.timeTv.setVisibility(View.GONE);
            orderListReq.setPaymentTime(objects);
            binding.idEtInput.setText("");
            getOrderList();
        });
        binding.btnSearch.setOnClickListener(view -> {
            orderListReq.setOrderId(binding.idEtInput.getText().toString());
            getOrderList();
        });
    }

    public void getOrderList() {
        LoadingUtils.showProgressDialog(OrderFormActivity.this, "温馨提示", "加载中，请稍后");
        List<Integer> objects = new ArrayList<>();
        if (Constants.AppConstVars.SnInfo!=null){
            objects.add(Constants.AppConstVars.SnInfo.getFItemID());
        }
        orderListReq.setPosId(objects);
        OrderListTask orderListTask = new OrderListTask(FormDataUtils.buildFormData(orderListReq));
        orderListTask.setHandler(orderListHandler);
        orderListTask.execute();
    }

    OrderFormAdapter.OnItemClickListener orderItemClick = orderId -> {
        Bundle bundle = new Bundle();
        bundle.putString("orderId", orderId);
        gotoActivity(OrderDetailActivity.class, bundle);
    };


    //    // 滚动到底事件
//    RecyclerView.OnScrollListener orderListScroll = new RecyclerView.OnScrollListener() {
//        @Override
//        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//            super.onScrolled(recyclerView, dx, dy);
//            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//
//            // 只处理 LinearLayoutManager（如果你用 GridLayoutManager 也可以用同样方式）
//            if (layoutManager instanceof LinearLayoutManager) {
//                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
//                int visibleItemCount = linearLayoutManager.getChildCount();               // 可见 item 数量
//                int totalItemCount = linearLayoutManager.getItemCount();                 // 总 item 数
//                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition(); // 最后可见 item 的 position
//                // ✅ 判断是否滑动到底部
//                if ((visibleItemCount + lastVisibleItemPosition) >= totalItemCount && dy > 0) {
//                    // 触底事件触发
//                    Log.d("RecyclerView", "已滑动到底部");
////                    orderListReq.setPage(orderListReq.getPage() + 1);
////                    getOrderList();
//                    // 👉 你可以在这里执行分页加载 / 请求接口
//                }
//            }
//        }
//    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        if (startDialog != null) {

            startDialog.dismiss();
        }
    }
}